package com.blue.code.db.ftl;

import java.io.File;
import java.util.List;
import java.util.Locale;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;

import com.blue.code.db.bean.EntityBean;
import com.blue.code.db.src.Parser;
import com.blue.code.db.src.Table;

import freemarker.template.Configuration;

public class FtlHandler implements InitializingBean
{
	private static Logger logger = LoggerFactory.getLogger(FtlHandler.class);
	
	@Value("${ftl.ext}")
	private String ext;
	@Value("${output.pkg}")
	private String pkg;
	@Value("${output.path}")
	private String output;
	
	@Resource
	private Parser parser;
	
	private List<Handler> handlerList;
	private Configuration conf;
	
	public FtlHandler()
	{
	}
	
	public void handle() throws Exception
	{
		if (handlerList == null || handlerList.isEmpty())
		{
			logger.warn("没有定义处理器");
			return;
		}
		List<Table> tableList = parser.parse();
		if (tableList == null || tableList.isEmpty())
		{
			logger.warn("没有找到数据表");
			return;
		}
		for (Handler handler : handlerList)
		{
			handler.initConfiguration(conf, ext);
			for (Table table : tableList)
			{
				EntityBean bean = EntityBean.toEntity(table);
				handler.handle(bean, output, pkg);
			}
		}
	}

	public void setHandlers(List<Handler> list)
	{
		this.handlerList = list;
	}
	
	@Override
	public void afterPropertiesSet() throws Exception
	{
		String path = FtlHandler.class.getResource("/").getPath();
		conf = new Configuration(Configuration.getVersion());
		conf.setEncoding(Locale.CHINA, "UTF-8");
		File file = new File(path + "ftl/");
		if (!file.exists())
		{
			logger.error("模板目录不存在");
			return;
		}
		conf.setDirectoryForTemplateLoading(file);
		
		File dir = new File(output);
		if (!dir.exists())
			dir.mkdirs();
		
		this.handle();
		/*List<Table> tableList = parser.parse();
		String json = JsonUtil.output(tableList);
		System.out.println(json);*/
	}
	
}
